package com.lml.hydrogenexpertsystem.backend.controller;

import com.lml.hydrogenexpertsystem.backend.annotation.AuthCheck;
import com.lml.hydrogenexpertsystem.backend.constant.UserConstant;
import com.lml.hydrogenexpertsystem.backend.service.AIService;
import com.lml.hydrogenexpertsystem.backend.service.VectorService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

/**
 * @author 梦龙
 * @date 2025/4/14 17:34
 */
@RestController
@RequestMapping("/qa")
public class QAController {
    private final VectorService vectorService;
    private final AIService aiService;

    public QAController(VectorService vectorService, AIService aiService) {
        this.vectorService = vectorService;
        this.aiService = aiService;
    }

    @PostMapping("/ask")
//    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @AuthCheck(mustRole = UserConstant.DEFAULT_ROLE)
    public ResponseEntity<Map<String, Object>> handleQuestion(@RequestBody Map<String, String> request) {
        String question = request.get("question");
        try {
            List<String> context = vectorService.getContextDocuments(question);
            String answer = aiService.generateAnswer(question, context);
            return ResponseEntity.ok().body(Map.of(
                    "status", "success",
                    "answer", answer,
                    "context", context
            ));
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(Map.of(
                    "status", "error",
                    "message", e.getMessage()
            ));
        }
    }
}